package com.sh.cloudrender.domian.service.kube;

import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PodService {

    @Autowired
    private CoreV1Api coreV1Api;

    public List<V1Pod> listBy(String uid, String namespace) {
        V1PodList podList = null;
        try {
            podList = coreV1Api.listNamespacedPod(namespace, null, null, null,
                    null, StringUtils.isBlank(uid) ? null : "uid=" + uid, null, null, null, null, false);
        } catch (ApiException e) {

        }

        if (podList == null || podList.getItems().isEmpty()) {
            return null;
        }

        return podList.getItems();
    }

    public V1Pod getOne(String uid, String namespace){
        V1PodList podList = null;
        try {
            podList = coreV1Api.listNamespacedPod(namespace, null, null, null,
                    null, StringUtils.isBlank(uid) ? null : "uid=" + uid, null, null, null, null, false);
        } catch (ApiException e) {

        }

        if (podList == null || podList.getItems().isEmpty()) {
            return null;
        }

        return podList.getItems().get(0);
    }

    public boolean exist(String uid, String namespace) {
        if (CollectionUtils.isEmpty(listBy(uid, namespace))) {
            return false;
        }

        return true;
    }
}
